Skip to main content

Code implementation

Experiment-implementation

With all the necessary components now set up, it's time to save your experiment configuration as a DRAFT. We've provided implementation examples in various programming languages, so you can select the one that suits your project. Incorporate this into your codebase, and also refer to your project's SDK documentation for additional guidance.

For example see end-to-end ReactJS Implementation
import React, { useState, useEffect } from 'react';

const ExperimentComponent = () => {
// Default banner state is set to 'current_deal', which acts as the control variant or baseline.
const [banner, setBanner] = useState('current_deal');

useEffect(() => {
async function fetchExperiment() {
try {
// Fetching the experiment data using the Percept SDK.
// 'DemoExperiment' is the name of the experiment being conducted.
const experiment = await Percept.getExperiment('DemoExperiment');

// Check the variant assigned to the current user.
// Based on the variantName, the banner is updated to reflect the specific deal.
if (experiment?.variantName === 'startup') {
// If the user is in the 'startup' variant group, show 'startup_deals' banner.
setBanner('startup_deals');
} else if (experiment?.variantName === 'lifetime') {
// If the user is in the 'lifetime' variant group, show 'lifetime_deals' banner.
setBanner('lifetime_deals');
} else {
// If no variant is returned (or an error occurs), fall back to the control variant.
// Ensuring the control variant as the default behavior helps in avoiding application failures.
}
} catch (error) {
// Log any errors encountered while fetching the experiment data.
console.error('Error fetching experiment:', error);
// In case of an error, the control variant ('current_deal') remains as the default banner.
}
}

// Trigger the experiment fetch on component mount.
fetchExperiment();
}, []);

return (
<div>
{/* Display the banner based on the variant assigned to the user. */}
<h1>{banner}</h1>
</div>
);
};

export default ExperimentComponent;
For example see end-to-end Flutter Implementation
import 'package:flutter/material.dart';

class ExperimentComponent extends StatefulWidget {
@override
_ExperimentComponentState createState() => _ExperimentComponentState();
}

class _ExperimentComponentState extends State<ExperimentComponent> {
String banner = 'current_deal'; // Default banner is 'current_deal', which acts as the control variant.

@override
void initState() {
super.initState();
fetchExperiment();
}

Future<void> fetchExperiment() async {
try {
// Fetching the experiment data using the Percept SDK.
// 'DemoExperiment' is the name of the experiment being conducted.
final experiment = await Percept.getExperiment('DemoExperiment');

// Check the variant assigned to the current user and update the banner.
if (experiment != null) {
setState(() {
if (experiment.variantName == 'startup') {
banner = 'startup_deals'; // Show 'startup_deals' banner for 'startup' variant.
} else if (experiment.variantName == 'lifetime') {
banner = 'lifetime_deals'; // Show 'lifetime_deals' banner for 'lifetime' variant.
}
// Control variant ('current_deal') is used by default if no valid variant is found.
});
}
} catch (error) {
// Log any errors and keep the control variant as default.
print('Error fetching experiment: $error');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Experiment Banner'),
),
body: Center(
// Display the banner based on the variant assigned to the user.
child: Text(
banner,
style: TextStyle(fontSize: 24),
),
),
);
}
}

void main() {
runApp(MaterialApp(
home: ExperimentComponent(),
));
}
For example see end-to-end React Native Implementation
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

const ExperimentComponent = () => {
const [banner, setBanner] = useState('current_deal'); // Default to 'current_deal' control variant.

useEffect(() => {
const fetchExperiment = async () => {
try {
// Fetching the experiment data using the Percept SDK.
const experiment = await Percept.getExperiment('DemoExperiment');

// Check the variant assigned to the current user and update the banner.
if (experiment?.variantName === 'startup') {
setBanner('startup_deals'); // Set banner to 'startup_deals' for 'startup' variant.
} else if (experiment?.variantName === 'lifetime') {
setBanner('lifetime_deals'); // Set banner to 'lifetime_deals' for 'lifetime' variant.
}
} catch (error) {
console.error('Error fetching experiment:', error);
// On error, fallback to the control variant ('current_deal').
}
};

// Fetch the experiment when the component mounts.
fetchExperiment();
}, []);

return (
<View style={styles.container}>
{/* Display the banner based on the variant assigned to the user. */}
<Text style={styles.bannerText}>{banner}</Text>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
bannerText: {
fontSize: 24,
fontWeight: 'bold',
},
});

export default ExperimentComponent;

You can retrieve experiment data at any time using the getExperiment method. This method returns a promise that resolves to the variant data for the specified experiment. Depending on the variant assigned to the user, you can implement different behaviors in your application.

When you fetch an experiment, you'll receive an object containing several key properties that you can utilize:

  • experimentId: A unique identifier for the experiment.
  • experimentName: The name of the experiment.
  • variantId: A unique identifier for the variant assigned to the user.
  • variantName: The name of the variant assigned to the user.
  • variantWeight: The distribution weight of the variant, indicating the proportion of users who should receive this variant.
  • payload: A Record<string, any> that may contain additional data specific to the variant. This can be used to pass extra information or settings that need to be evaluated during the experiment.